import java.util.LinkedList;
import java.util.Queue;

/**
 * 1162. 地图分析
 * https://leetcode.cn/problems/as-far-from-land-as-possible/description/
 */
class Solution {
    int[] dx = {0, 0, -1, 1};
    int[] dy = {-1, 1, 0, 0};
    int m, n;
    boolean[][] vist;
    public int maxDistance(int[][] grid) {
        m = grid.length; n = grid[0].length;
        vist = new boolean[m][n];
        Queue<int[]> q = new LinkedList<>();

        //先遍历一遍数组，找到陆地，值改为0，加入队列并标记
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    grid[i][j] = 0;
                    q.add(new int[]{i, j});
                    vist[i][j] = true;
                }
            }
        }
        //判断是否都是陆地或海洋
        if(q.isEmpty() || q.size() == m * n) {
            return -1;
        }

        //多源bfs
        int  ret = 0;
        while(!q.isEmpty()) {
            int[] tmp = q.poll();
            int a = tmp[0], b = tmp[1];
            for(int i = 0; i < 4; i++) {
                int x = a + dx[i], y = b + dy[i];
                if(x >= 0 && x < m && y >= 0 && y < n && !vist[x][y]) {
                    q.add(new int[]{x, y});
                    vist[x][y] = true;
                    grid[x][y] = grid[a][b] + 1;
                    ret = Math.max(ret, grid[x][y]);
                }
            }
        }
        return ret;
    }
}